package com.wswy.wzcx.ui.other;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

public class FineNoTextWatcher implements TextWatcher {
    private static final char SEPARATOR = ' ';

    private EditText editText;

    public FineNoTextWatcher(EditText editText) {
        this.editText = editText;
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

        if (s == null || s.length() == 0) {
            return;
        }
        StringBuilder sb = new StringBuilder();

        int len = s.length();

        for (int i = 0; i < len; i++) {
            if (i != 4 && i != 9 && i != 14 && s.charAt(i) == SEPARATOR){

            }else {
                sb.append(s.charAt(i));

                int newLen = sb.length();

                if ((newLen % 5 == 0) &&  sb.charAt(newLen - 1) != SEPARATOR){
                    sb.insert(newLen - 1, SEPARATOR);
                }
            }

        }

        if (!TextUtils.equals(sb,s)) {
            int index = start + 1;
            if (sb.charAt(start) == SEPARATOR) {
                if (before == 0) {
                    index++;
                } else {
                    index--;
                }
            } else {
                if (before == 1) {
                    index--;
                }
            }
            editText.setText(sb.toString());
            editText.setSelection(index);
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    public static String getRealFineNumber(EditText editText) {
        Editable text = editText.getText();
        if (TextUtils.isEmpty(text)) {
            return null;
        }
        return text.toString().replaceAll(String.valueOf(SEPARATOR), "");
    }
    
}
